package com.shiny.concurrency4java.singleton;

import com.shiny.concurrency4java.util.Constant;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

@Slf4j
public class SingletonExample0 {

    private volatile static SingletonExample0 mInstance;

    private SingletonExample0(){
        log.info("SingletonExample0 function start");
    }

    public static SingletonExample0 getInstance(){
        if ( mInstance == null ) {
            synchronized (SingletonExample0.class) {
                if (mInstance == null) {
                    mInstance = new SingletonExample0();
                }
            }
        }
        return mInstance;
    }

    public static void main(String[] args) throws Exception {
        ExecutorService executorService = Executors.newCachedThreadPool();
        final Semaphore semaphore = new Semaphore(Constant.threadTotal);
        final CountDownLatch countDownLatch = new CountDownLatch(Constant.clientTotal);
        for (int i = 0; i < Constant.clientTotal ; i++) {
            executorService.execute(() -> {
                try {
                    semaphore.acquire();
                    SingletonExample0.getInstance();
                    semaphore.release();

                } catch (Exception e) {
                    log.error("exception", e);
                }
                countDownLatch.countDown();
            });
        }
        countDownLatch.await();
        executorService.shutdown();
    }


}
